package com.aizuda.limiter.example.distributed;

import com.aizuda.limiter.extend.IDistributedLockListener;
import com.aizuda.limiter.metadata.MethodMetadata;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author zhongjiahua
 * @date 2021-12-06
 * @Description:
 */
@Component
@Slf4j
public class CustomerDistributedLockListener implements IDistributedLockListener {
    private ThreadLocal<LockInfo> lockInfoThreadLocal = new ThreadLocal<>();

    @Override
    public boolean supports(MethodMetadata methodMetadata) {
        return "com.aizuda.limiter.example.distributed.LockTestComponent.testLockListener".equals(methodMetadata.getClassMethodName());
    }

    @Override
    public void beforeDistributedLock(MethodMetadata methodMetadata, String lockKey) {
        lockInfoThreadLocal.set(new LockInfo().setLockKey(lockKey));
    }

    @Override
    public void afterDistributedLock(MethodMetadata methodMetadata, String lockKey) {
        lockInfoThreadLocal.get().setAcquireLockSuccessBool(true);
    }

    @Override
    public void afterExecute(MethodMetadata methodMetadata, String lockKey, Object result) {
        lockInfoThreadLocal.get().setExecuteMethodSuccessBool(true);
    }

    @Override
    public void distributedLockFinally(MethodMetadata methodMetadata, String lockKey) {
        LockInfo lockInfo = lockInfoThreadLocal.get();
        log.info("当前分布式锁 key：【{}】，是否获取锁：【{}】，是否执行实际的逻辑：【{}】", lockInfo.getLockKey(),
                lockInfo.isAcquireLockSuccessBool(), lockInfo.isExecuteMethodSuccessBool());
        lockInfoThreadLocal.remove();
    }
}
